<template>
    <BPTable v-if="init" ref='tableRef' align='center' row-key='id' :columns='columns' :api='pageApi' :buttons='buttons' :rowSelection="true" :selection-buttons="selectionButtons" @selectionChange="selectionChange">
        
        <template #$selection>
            <a-button v-if="resourceStore.hasPermission('device:unbind:tenant')" @click="batchUnbindTenant">{{ $c('unbind', 'owner') }}</a-button>
            <a-button v-if="resourceStore.hasPermission('device:bind:tenant')" type="primary" @click="batchBindTenantVisible = true">{{ $c('bind', 'owner') }}</a-button>
            <a-button type="primary" @click="pushSetting">推送设备运行参数</a-button>
        </template>

        <template #chargeType="{record}">
            {{ chargingTypeMap[record.chargeType] }}
        </template>

        <template #connectStatus="{record}">
            <a-tag v-if="record.connectStatus == 0" :bordered="false" color="error">离线</a-tag>
            <a-tag v-else :bordered="false" color="success">在线</a-tag>
        </template>

        <template #$action='{record}'>
            <BTextButton @click="openDetail(record)">详情</BTextButton>
        </template>
    </BPTable>

    <BDialog v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit' @close="resetForm">
        <a-form ref='formRef' :label-col='{span : 5}' :model='formData'>
            <a-form-item style='display:none' name='id'>
                <a-input type='hidden' v-model:value='formData.id' />
            </a-form-item>
            <a-form-item label="设备名" name="name">
                <a-input type='text' v-model:value='formData.name' />
            </a-form-item>
            <!-- <a-form-item label="运行参数" name="paramsRule">
                <a-select v-model:value="formData.paramsRule" :fieldNames="{label : 'name', value : 'id'}" :options="paramsOptions"></a-select>
            </a-form-item>
            <a-form-item label="收费标准" name="pricing">
                <a-select v-model:value="formData.pricing" :fieldNames="{label : 'name', value : 'id'}" :options="slowChargePricingOptions"></a-select>
            </a-form-item>
            <a-form-item :label="$t('owner')" name="owner">
                <FetchSelect v-model="formData.owner" allowClear label-field="name" value-field="id" options-field="children" :fetch="querySubTenant" />
            </a-form-item> -->
        </a-form>
    </BDialog>


    <a-drawer width="800px" destroyOnClose v-model:open="isOpenDetail">
        <Detail :device="currentDetail" />
    </a-drawer>

</template>

<script lang='ts' setup>
    import { pageApi, saveApi, batchUnbindTenantApi, batchBindTenantApi, chargingTypeApi, sendDeviceSetting } from '@/api/devices/Device'
    import { optionsApi as paramsOptionsApi } from '@/api/Devices/Params'
    import { optionsApi as slowChargePricingOptionsApi } from '@/api/pricingRule/Slow'
    import { useI18nStore } from '@/store/i18n'
    import { useResourceStore } from '@/store/resource'
    import { message, Modal } from 'ant-design-vue'
    import { nextTick, ref } from 'vue'
    import FetchSelect from '@/components/FetchSelect.vue'
    import { querySubTenantApi } from '@/api/system/Tenant';
    import { recursionFn } from '@/utils'
    import Detail from './Detail.vue'


    const isOpenDetail = ref(false)
    const currentDetail = ref<any>()
    function openDetail(row) {
        currentDetail.value = row
        isOpenDetail.value = true
    }


    const i18n = useI18nStore()
    const resourceStore = useResourceStore()

    const visible = ref(false)

    const tableRef = ref()
    const formRef = ref()
    const dialogTitle = ref()


    const init = ref(false)

    //所选的行
    const selectedKeys = ref<any[]>([])
    function selectionChange(keys:any[], rows:any[]) {
        selectedKeys.value = keys
    }


    //批量绑定
    const batchBindTenantVisible = ref(false)
    const batchBindFormRef = ref()
    const batchBindFormData = ref({
        owner : ''
    })
    
    async function batchBindSubmit() {
        let { owner } = await batchBindFormRef.value.validate()
        const res = await batchBindTenantApi(selectedKeys.value, owner)

        if(res.success) {
            batchBindTenantVisible.value = false
            message.success(i18n.t('executeSuccess'))
            tableRef.value.load()
            
        }else {
            message.error(res.msg)
        }
    }

    function closeBatchBind() {
        batchBindFormRef.value.clearValidate()
        batchBindFormRef.value.resetFields()
        
    }

    //批量解绑
    function batchUnbindTenant() {
        Modal.confirm({
            title : i18n.t('confirmExecute'),
            async onOk() {
                const res = await batchUnbindTenantApi(selectedKeys.value)

                if(res.success) {
                    message.success(i18n.t('executeSuccess'))
                    tableRef.value.load()
                }else {
                    message.error(res.msg)
                }
                
            }
        })
    }


    //运行参数
    const paramsOptions = ref<any[]>([])
    function queryParamsOptions() {
        if(paramsOptions.value.length == 0) {
            paramsOptionsApi().then(res => {
                if(res.data) {
                    paramsOptions.value = res.data
                }
            })
        }
        
    }


    //收费标准
    const slowChargePricingOptions = ref<any[]>([])
    function querySlowChargePricingOptions() {
        if(slowChargePricingOptions.value.length == 0) {
            slowChargePricingOptionsApi().then(res => {
                if(res.data) {
                    slowChargePricingOptions.value = res.data
                }
            })
        }
        
    }


    function pushSetting() {
        Modal.confirm({
            content: '确定推送吗',
            okText: '确定',
            async onOk() {
                
                await sendDeviceSetting(selectedKeys.value)
            }
        });
    }


    async function submit() {
        let { id, ...params} = await formRef.value.validate()
        


        if(id) {
            params.id = Number(id)
        }

        

        const res = await saveApi(params)
        if(res.success) {
            resetForm()
            visible.value = false
            message.success(i18n.t('saveSuccess'))
            tableRef.value.load()
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }



    const chargingTypeOptions = ref<any[]>([])
    const chargingTypeMap = ref<{[key:string]:string}>({})

    const formData = ref({
        id : 0,
        name : '',
        paramsRule : '',
        pricing : '',
        owner : '',
    })


    const buttons = ref<SearchButton[]>([])
    const selectionButtons = ref<SelectionButton[]>([])

    

    buttons.value.push({
        button : 'export',
        func : () => {
            dialogTitle.value = i18n.t('add')
            visible.value = true
        }
    })

    // if(resourceStore.hasPermission('devices:device:batch:delete')) {
    //     selectionButtons.value.push({
    //         button : 'delete',
    //         func : async () => {
    //             console.log('333333333')
    //         }
    //     })
    // }






    async function querySubTenant(query:string|number, init:boolean = false) {
        const params:any = {}

        if(init) {
            if(!query) return
            params.id = query
        }else {
            params.name = query
        }

        let res = await querySubTenantApi(params)
        return res.data
    }


    function resetForm() {
        formRef.value.clearValidate()
        formRef.value.resetFields()
    }

    

    const columns = ref<Column[]>([
        {
            title : i18n.t('code'),
            dataIndex : 'id',
            align : 'center',
            inSearch : true,
        },

        {
            title : i18n.t('name'),
            dataIndex : 'name',
            align : 'center',
        },

        {
            title : '端口数',
            dataIndex : 'portCount',
            align : 'center',
        },

        {
            title : '链接状态',
            dataIndex : 'connectStatus',
            align : 'center',
            inSearch : true,
            type : 'select',
            options : [
                {value : 1, label : '在线'},
                {value : 0, label : '离线'}
            ]
        },

        {
            title : '充电类型',
            dataIndex : 'chargeType',
            align : 'center',
            inSearch : true,
            type : 'select',
            name : 'chargeType',
            labelField : 'name',
            valueField : 'code',
            optionsField : 'children',
            options : chargingTypeOptions,
            attrs : {
                fieldNames : {
                    label : 'name',
                    value : 'code',
                    options : 'children'
                },

                mode : 'multiple'

                //multiple : true,
            }
        },


        {
            title : i18n.t('owner'),
            dataIndex : 'ownerName',
            align : 'center',
            inSearch : true,
            name : 'owner',
            type : 'fetchSelect',
            valueField : 'id',
            labelField : 'name',
            optionsField : 'children',
            fetchApi : querySubTenant
        },

        {
            title : i18n.t('action'),
            dataIndex : '$action',
            align : 'center',
            $edit : resourceStore.hasPermission('device:update:info') ? (row) => {
                queryParamsOptions()
                querySlowChargePricingOptions()
                dialogTitle.value = i18n.t('edit')
                
                for(let k in formData.value) {
                    if(k == 'type') {
                        formData.value[k] = String(row[k])
                    }else {
                        if(k == 'pricing' || k == 'paramsRule' || k == 'longitude' || k == 'latitude') {
                            if(row[k] == 0) {
                                formData.value[k] = ''
                                continue
                            }
                        }

                        formData.value[k] = row[k]
                    }
                    
                }

                visible.value = true
            } : undefined,

        }
    ])


    

    chargingTypeApi().then(res => {
        if(res.data.length > 0) {
            res.data.forEach(item => {
                chargingTypeMap.value[item.code] = i18n.t(item.name)
                item.code = Number(item.code)
                item.name = i18n.t(item.name)
            })

            let options = recursionFn(res.data, 0, 'id', 'parentId', 'children')


            chargingTypeOptions.value = options
        }

        nextTick(() => {
            init.value = true
        })
    })

</script>

<style lang='scss' module>
    .username{
        display: inline-flex;
        align-items: center;
        gap: 10px;
    }
</style>